package com.nulldev.util.networking.rudpEnhanced;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.Variables;

public class rUDPEPacket implements rUDPEPacketFlags {

	public static final short HEADER = 0xABA;

	/*
	 * PACKET FORMAT
	 * 
	 * HEADER PACKET FLAG COUNT PACKET FLAG(s) PACKET FLAG DATA LENGTH PACKET FLAG
	 * DATA PACKET LENGTH PACKET DATA
	 * 
	 */

	private int[] packet_flags = new int[0];
	private String packetID;
	private byte[] raw_data;
	private byte[] data;

	public String getPacketID() {
		return this.packetID;
	}

	public rUDPEPacket readPacket(final byte[] data) throws IOException {
		Variables.notNullE(data);
		if (data.length == 0)
			throw new IllegalArgumentException("data.length == 0!");
		this.raw_data = data;
		final ByteArrayInputStream bais = new ByteArrayInputStream(data);
		final DataInputStream dis = new DataInputStream(bais);
		final int header = dis.readInt();
		if (header != HEADER) {
			throw new UnsupportedOperationException("rUDPe: Invalid packet! [header=" + header + "]");
		}
		this.packetID = dis.readUTF();
		final int packet_flag_count = dis.readInt();
		if (packet_flag_count < 0)
			throw new UnsupportedOperationException("rUDPe: Invalid packet flag count! [packet_flag_count=" + packet_flag_count + "]");
		this.packet_flags = new int[packet_flag_count];
		if (packet_flag_count > 0) {
			for (int i = 0; i < packet_flag_count; i++) {
				this.packet_flags[i] = dis.readInt();
			}
		}
		final int size = dis.readInt();
		if (size < 0) {
			throw new UnsupportedOperationException("rUDPe: Invalid size count! [size=" + size + "]");
		}
		byte[] _data = new byte[size];
		dis.read(_data);
		this.data = _data;
		dis.close();
		try (final DataInputStream _dis = new DataInputStream(new ByteArrayInputStream(this.data))) {
			this.onPacket(_dis);
		} catch (Exception e) {
			JVM.errorln(e);
		}
		return this;
	}

	public void onPacket(final DataInputStream dis) throws IOException {
	}

	public void onGenerate(final DataOutputStream dos) throws IOException {
	}

	@Override
	public String toString() {
		return "rUDPe[id=" + this.packetID + ",size=" + this.data.length + "]";
	}
}
